import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  Button,
  Chip,
  Divider,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  ListItemButton,
  Collapse,
  Paper,
  IconButton,
  Tooltip,
} from '@mui/material';
import {
  ExpandLess,
  ExpandMore,
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  PlayArrow as PlayIcon,
  Pause as PauseIcon,
  Refresh as RefreshIcon,
  Settings as SettingsIcon,
  Assessment as AssessmentIcon,
  History as HistoryIcon,
  ViewModule as TemplateIcon,
  Rule as RuleIcon,
  Description as LogIcon,
} from '@mui/icons-material';
import { Iconify } from 'src/components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';
import { AutoAccountingRuleList } from './auto-accounting-rule-list';
import { AutoAccountingTemplates } from './auto-accounting-templates';
import { AutoAccountingExecutionLogs } from './auto-accounting-execution-logs';
import { AutoAccountingRuleCreateDialog } from './auto-accounting-rule-create-dialog';
import { AutoAccountingBatchActions } from './auto-accounting-batch-actions';

// 菜单项类型定义
interface MenuItem {
  id: string;
  title: string;
  icon: React.ReactNode;
  component: React.ReactNode;
  description: string;
  actions?: React.ReactNode;
}

export function AutoAccountingView() {
  const [selectedMenu, setSelectedMenu] = useState<string>('rules');
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  // 菜单配置
  const menuItems: MenuItem[] = [
    {
      id: 'rules',
      title: '规则管理',
      icon: <RuleIcon />,
      component: <AutoAccountingRuleList refreshTrigger={refreshTrigger} />,
      description: '管理自动记账规则，包括创建、编辑、删除和启用/禁用规则',
      actions: (
        <Box display="flex" gap={1}>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => setCreateDialogOpen(true)}
            size="small"
          >
            新建规则
          </Button>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => setRefreshTrigger(prev => prev + 1)}
            size="small"
          >
            刷新
          </Button>
        </Box>
      ),
    },
    {
      id: 'templates',
      title: '模板管理',
      icon: <TemplateIcon />,
      component: <AutoAccountingTemplates />,
      description: '管理规则模板，快速创建常用规则',
      actions: (
        <Box display="flex" gap={1}>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            size="small"
          >
            新建模板
          </Button>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            size="small"
          >
            刷新
          </Button>
        </Box>
      ),
    },
    {
      id: 'execution-logs',
      title: '执行日志',
      icon: <LogIcon />,
      component: <AutoAccountingExecutionLogs />,
      description: '查看自动记账规则的执行历史和结果',
      actions: (
        <Box display="flex" gap={1}>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => setRefreshTrigger(prev => prev + 1)}
            size="small"
          >
            刷新
          </Button>
        </Box>
      ),
    },
  ];

  // 获取当前选中的菜单项
  const selectedMenuItem = menuItems.find(item => item.id === selectedMenu);

  // 处理菜单选择
  const handleMenuSelect = (menuId: string) => {
    setSelectedMenu(menuId);
  };

  // 处理创建成功
  const handleCreateSuccess = () => {
    setCreateDialogOpen(false);
    setRefreshTrigger(prev => prev + 1);
  };

  return (
    <DashboardContent maxWidth="xl">
      <Grid container spacing={3}>
        {/* 左侧菜单区域 */}
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent sx={{ p: 0 }}>
              <Typography variant="h6" sx={{ p: 2, pb: 1.5, borderBottom: 1, borderColor: 'divider', backgroundColor: 'grey.50' }}>
                功能菜单
              </Typography>
              <List sx={{ p: 4 }}>
                {menuItems.map((item, index) => (
                  <React.Fragment key={item.id}>
                    <ListItem sx={{ p: 0, mb: 4 }}>
                      <ListItemButton
                        selected={selectedMenu === item.id}
                        onClick={() => handleMenuSelect(item.id)}
                        sx={{
                          borderRadius: 4,
                          py: 4,
                          px: 4,
                          width: '100%',
                          backgroundColor: 'background.paper',
                          border: '2px solid',
                          borderColor: 'divider',
                          minHeight: 100,
                          '&.Mui-selected': {
                            backgroundColor: 'primary.light',
                            color: 'primary.contrastText',
                            borderColor: 'primary.main',
                            '&:hover': {
                              backgroundColor: 'primary.main',
                            },
                          },
                          '&:hover': {
                            backgroundColor: 'action.hover',
                            transform: 'translateY(-3px)',
                            boxShadow: 6,
                            borderColor: 'primary.light',
                          },
                          transition: 'all 0.3s ease-in-out',
                        }}
                      >
                        <ListItemIcon sx={{ color: 'inherit', minWidth: 64, mr: 2.5 }}>
                          {item.icon}
                        </ListItemIcon>
                        <ListItemText 
                          primary={item.title}
                          primaryTypographyProps={{
                            fontWeight: selectedMenu === item.id ? 'bold' : 'normal',
                            fontSize: '1.2rem',
                          }}
                        />
                      </ListItemButton>
                    </ListItem>
                    {/* 在菜单项之间添加更明显的分隔线和间距（除了最后一个） */}
                    {index < menuItems.length - 1 && (
                      <Box sx={{ mx: 2, my: 3 }}>
                        <Divider sx={{ borderWidth: 3, borderColor: 'grey.400' }} />
                      </Box>
                    )}
                  </React.Fragment>
                ))}
              </List>
            </CardContent>
          </Card>
        </Grid>

        {/* 右侧内容区域 */}
        <Grid item xs={12} md={9}>
          <Card>
            <CardContent sx={{ p: 0 }}>
              {/* 页面标题和操作按钮 */}
              <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider' }}>
                <Box display="flex" justifyContent="space-between" alignItems="center">
                  <Box>
                    <Typography variant="h6" component="h2">
                      {selectedMenuItem?.title}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {selectedMenuItem?.description}
                    </Typography>
                  </Box>
                  {selectedMenuItem?.actions}
                </Box>
              </Box>

              {/* 内容区域 */}
              <Box sx={{ p: 2 }}>
                {selectedMenuItem?.component}
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 创建规则对话框 */}
      <AutoAccountingRuleCreateDialog
        open={createDialogOpen}
        onClose={() => setCreateDialogOpen(false)}
        onSuccess={handleCreateSuccess}
      />
    </DashboardContent>
  );
}
